/**
 * 将Blob转换为File对象
 * @param {Blob} blob - 需要转换的Blob对象
 * @param {string} fileName - 转换后的文件名
 * @returns {File} 返回转换后的File对象
 */
const blobToFile = (blob: Blob, fileName: string) => {
    return new File([blob], fileName, { type: blob.type });
}

interface CompressOption {
    compressMaxNum?: number;
    quality?: number;
    maxWidth?: number;
    maxSize?: number; // 单位kb, 如果填写的是 -1 那么就只看 compressMaxNum 的次数
}

interface CompressPictureResult {
    filename: string;
    size: number;
    file: File;
    blob: Blob;
    base64: string;
}


export const compressPicture = (file: File, option?: CompressOption) => {
    return new Promise<CompressPictureResult>((resolve, reject) => {
        const opt: Required<CompressOption> = {
            compressMaxNum: 3,
            quality: 0.8,
            maxWidth: 800,
            maxSize: 1024,
            ...option,
        }

        let compressNum = 0;

        // 压缩
        const _compress = (file: File) => {

            // 创建FileReader对象来读取文件
            const reader = new FileReader();
            reader.onload = (e: ProgressEvent<FileReader>) => {
                const img = new Image();
                img.onload = () => {
                    // 创建canvas元素
                    const canvas = document.createElement("canvas");
                    const ctx = canvas.getContext("2d");

                    // 计算压缩比例
                    const MAX_WIDTH = opt.maxWidth ? opt.maxWidth : img.width;
                    let width = img.width;
                    let height = img.height;
                    if (width > height) {
                        if (width > MAX_WIDTH) {
                            height *= MAX_WIDTH / width;
                            width = MAX_WIDTH;
                        }
                    } else {
                        if (height > MAX_WIDTH) {
                            width *= MAX_WIDTH / height;
                            height = MAX_WIDTH;
                        }
                    }

                    // 设置canvas尺寸
                    canvas.width = width;
                    canvas.height = height;

                    // 绘制图片并压缩
                    ctx!.drawImage(img, 0, 0, width, height);

                    canvas.toBlob((blob) => {
                        const size = blob?.size! / 1024;
                        compressNum++;
                        console.log(`[${file.name}] 第${compressNum}次压缩,压缩前:${file.size / 1024}kb, 压缩后:${size}kb`)
                        const _file = blobToFile(blob!, file.name)
                        if (opt.maxSize !== -1 && size > opt.maxSize && compressNum <= opt.compressMaxNum) {
                            return _compress(_file);
                        } else {
                            const base64 = canvas.toDataURL(file.type, opt.quality);
                            const _fileObj: any = {
                                filename: file.name,
                                size: file.size,
                                file: _file,
                                blob: blob,
                                base64: base64,
                            }
                            resolve(_fileObj)
                        }
                    }, file.type, 0.8)

                }
                img.onerror = (e) => {
                    reject(e);
                }
                img.src = e.target!.result as string;
            }
            reader.onerror = (e) => {
                reject(e)
            }
            // 读取文件为DataURL
            reader.readAsDataURL(file);

        }

        _compress(file)
    })

}

export const random = (min: number, max: number): number => {
    return Math.floor(Math.random() * (max - min + 1)) + min
}